package com.lightsaber.trade.core.service.account.impl;

import javax.persistence.NoResultException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.lightsaber.trade.core.dao.account.UserDao;
import com.lightsaber.trade.core.entity.account.User;

@Component
public class UserDetailsServiceImpl implements
        org.springframework.security.core.userdetails.UserDetailsService {
    private static final Logger log = Logger.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
            DataAccessException {

        User user = null;
        try {
            log.info("findUniqueBy: " + username);
            user = userDao.findUniqueBy("loginId", username);
            log.info("user: " + user);

            if (user == null) {
                throw new UsernameNotFoundException("not found user: " + username);
            }

        } catch (NoResultException ex) {
            throw new UsernameNotFoundException("not found user: " + username);
        }

        return new UserDetailsImpl(user);
    }

}
